<template>
	<view class="the-page">
		<view class="top">
			<uni-forms :label-width="90">
				<uni-forms-item label="收货人" required>
					<uni-easyinput type="text" v-model="addressInfo.name" placeholder="请填写收货人姓名"></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item label="手机号码" required>
					<uni-easyinput type="text" v-model="addressInfo.tel" placeholder="请填写收货人手机号"></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item label="所在地区" required>
					<uni-data-picker v-model="addressInfo.areaCode" popup-title="请选择地区" :localdata="areaList" @change="onChange">
					</uni-data-picker>
				</uni-forms-item>

				<uni-forms-item label="详细地址" required>
					<uni-easyinput type="text" v-model="addressInfo.detail" placeholder="街道乡村门号"></uni-easyinput>
				</uni-forms-item>

				<uni-forms-item label="邮政编码">
					<uni-easyinput type="number" v-model="addressInfo.postalCode" placeholder="邮政编码"></uni-easyinput>
				</uni-forms-item>
			</uni-forms>
		</view>

		<view class="bottom">
			<view class="left">
				<view class="set">设置默认地址</view>
				<view class="tips">提醒：每次下单会默认推荐该地址</view>
			</view>
			<view class="right">
				<switch :checked="addressInfo.isDefault" @change="addressInfo.isDefault=!addressInfo.isDefault" />
			</view>
		</view>
		<button type="primary" @click="onSave">保存</button>
		<br />
		<button type="error" v-if="!!id" @click="onDelete">删除</button>

	</view>
</template>

<script>
	import * as addressAPI from '@/api/address.js';
	import areaData from './areaFromVant.js';

	export default {
		data() {
			return {
				areaList: [], //				
				id: null, //Address.id
				addressInfo: {
					//收货人信息初始值
					id: null, //每条地址的唯一标识
					name: '', //姓名
					tel: '', //电话
					province: '', //省份
					city: '', //城市
					county: '', //区县
					areaCode: '', //地区编码，通过省市区选择获取（必填）
					postalCode: '', //邮政编码
					detail: '', //详细地址
					isDefault: false //是否选择默认
				}
			};
		},

		// 生命周期方法
		onLoad(options) {
			this.initAreaList(); // 按要求结构构建数据
			this.id = parseInt(options.id) || null;
			console.log("onLoad : this.id ", this.id)
			if (this.id) {
				// 编辑地址
				this.getAddressDetail();
			} else {
				// 新增地址
				this.initAddressDetail();
			}
		},
		methods: {
			onChange({ detail }) {
				const textList = detail.value.map(item => item.text)
				console.log("onChange", textList)
				this.addressInfo.province = textList[0] //省份
				this.addressInfo.city = textList[1] //城市
				this.addressInfo.county = textList[2] //区县
			},

			// 按要求结构构建数据，Vant的地区数据的编号是有父子规律的
			initAreaList() {
				this.areaList = [];
				// 省数据
				Object.entries(areaData.province_list).forEach(item => {
					//item是一个只有2个元素的数组
					this.areaList.push({
						value: item[0],
						text: item[1],
						children: [],
					});
				});
				// 市数据
				Object.entries(areaData.city_list).forEach(item => {
					//item是一个只有2个元素的数组
					let provinceId = item[0].substring(0, 2) + '0000';
					let province = this.areaList.find(item => item.value === provinceId)
					province && province.children.push({
						value: item[0],
						text: item[1],
						children: [],
					});
				});
				// 县区数据
				Object.entries(areaData.county_list).forEach(item => {
					//item是一个只有2个元素的数组
					let provinceId = item[0].substring(0, 2) + '0000';
					let cityId = item[0].substring(0, 4) + '00';
					let province = this.areaList.find(item => item.value === provinceId)
					let city = province && province.children.find(item => item.value === cityId)
					city && city.children.push({
						value: item[0],
						text: item[1],
					});
				});
			},

			//从后端获取地址数据
			getAddressDetail() {
				addressAPI.getDetailById(this.id).then(result => {
					this.addressInfo.id = result.data.id;
					this.addressInfo.name = result.data.name;
					this.addressInfo.tel = result.data.tel;
					this.addressInfo.province = result.data.province;
					this.addressInfo.city = result.data.city;
					this.addressInfo.county = result.data.county;
					this.addressInfo.areaCode = result.data.areaCode; //
					this.addressInfo.postalCode = result.data.postCode; //
					this.addressInfo.detail = result.data.detail; //
					this.addressInfo.isDefault = result.data.isDefault; //
					// 地区回填
					//this.setAreaByCode(this.addressInfo.areaCode);
				});
			},

			//初始地址
			initAddressDetail() {
				this.addressInfo.id = null, //每条地址的唯一标识
					this.addressInfo.name = '' //姓名
				this.addressInfo.tel = '' //电话
				this.addressInfo.province = '' //省份
				this.addressInfo.city = '' //城市
				this.addressInfo.county = '' //区县
				this.addressInfo.areaCode = '' //地区编码，通过省市区选择获取（必填）
				this.addressInfo.postalCode = '' //邮政编码
				this.addressInfo.detail = '' //详细地址
				this.addressInfo.isDefault = false //是否选择默认	
			},

			//处理保存地址
			onSave() {
				//准备参数
				let params = {
					id: this.addressInfo.id,
					name: this.addressInfo.name,
					tel: this.addressInfo.tel,
					province: this.addressInfo.province,
					city: this.addressInfo.city,
					county: this.addressInfo.county,
					areaCode: this.addressInfo.areaCode, //
					postalCode: this.addressInfo.postalCode, //
					detail: this.addressInfo.detail, //
					isDefault: this.addressInfo.isDefault //
				};

				addressAPI.save(params).then(result => {
					uni.showToast({ title: result.msg });
					//页面跳转
					setTimeout(() => {
						uni.navigateBack({
							delta: 1 //	url:'/pages/address/addressList'
						});
					}, 1000);
				});
			},
			// 处理删除地址
			onDelete() {
				uni.showModal({
					title: '提示',
					content: '确认是要删除了吗？',
					success: result => {
						if (result.confirm) {
							addressAPI.deleteById(this.id).then(() => {
								uni.navigateBack({
									delta: 1 //	url:'/pages/address/addressList'
								});
							});
						}
					}
				});
			}
		}
	};
</script>

<style lang="scss" scoped>
	.the-page {
		padding: 15px 15px 15px 15px;

		.top {
			padding: 22rpx;
		}

		.bottom {
			margin-top: 50rpx;
			padding: 40rpx;
			line-height: 64rpx;
			display: flex;
			justify-content: space-between;
			border-bottom: solid 2rpx $uni-border-color;

			.left {
				.set {
					font-size: 28rpx;
				}

				.tips {
					font-size: 24rpx;
				}
			}

			.right {}
		}
	}
</style>